const puppeteer = require('puppeteer');
const { parentPort,workerData } = require('worker_threads')

let timeout = 1000*60*60*12,lottery_data
async function start_grab(page){
    try{
        //page.goto('http://www.baidu.com/s?wd=彩票')
        await page.goto("http://kaijiang.500.com/?0_ala_baidu")
        const element = await page.waitForSelector('.kj_tablelist01')
        await lottery_new(element)
        //await lottery_history(element)
    }catch(e){
        console.log(e)
    }
}

async function lottery_history(element){
    parentPort.postMessage([])

    setTimeout(lottery_history, timeout, element)
}

async function lottery_new(element){
    const nums = await element.$$eval('.td_kjhm01 > .ball_box01', o=>o.map(t=>Array.prototype.map.call(t.children[0].children,x=>x.innerText)))
    const titles = await element.$$eval('.td_kjhm01 > .ball_box01',o=>o.map(t=>t.parentElement.previousElementSibling.previousElementSibling.previousElementSibling.innerText))
    const stages = await element.$$eval('.td_kjhm01 > .ball_box01',o=>o.map(t=>t.parentElement.previousElementSibling.previousElementSibling.innerText))
    const dates = await element.$$eval('.td_kjhm01 > .ball_box01',o=>o.map(t=>t.parentElement.previousElementSibling.innerText))
    
    let lottery = []
    for(let i=0;i<titles.length;i++){
        lottery.push([])
        lottery[i].push(titles[i])
        lottery[i].push(stages[i])
        lottery[i].push(dates[i])
        lottery[i].push(nums[i])
    }
    parentPort.postMessage(lottery)
}

async function run(){
    const browser = await puppeteer.launch({headless: true})
    const page = await browser.newPage()
    parentPort.on('message', o => lottery_data = o)
    parentPort.on('error', o => console.log('stock',o))
    parentPort.on('exit',async () => await browser.close())
    start_grab(page)
}
run()